package components {
	
	import com.smartfoxserver.v2.entities.Room;
	
	import events.SelectedSpeachChanged;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	
	public class SphereClient extends MovieClip {
		
		private var sphere:Sphere;	
		private var activePanel:ActivePanel;
		
		// current topic list
		private var dataArray:Array = new Array();
				
		public function SphereClient() {
			
			activePanel = new ActivePanel(this);
			addChild(activePanel);
		  
			// aligns
			//stage.scaleMode = StageScaleMode.NO_SCALE;
			//stage.align = StageAlign.TOP_LEFT;
			
			// generate data for the sphere
			/*var i:int;
			var elemCount:int = 10;
			for(i=0; i<elemCount; i++) {
				var b:Broadcast = new Broadcast();
				b.setName(i+1);
				dataArray.push(b);
			}*/
			
			// add sphere
			sphere = new Sphere(dataArray,this,10,150,dataArray.length);
			addChild(sphere);
			sphere.x = 200;//this.stage.stageWidth/3;
			sphere.y = 200;//this.stage.stageHeight/3;
		 
			// add rotation
			/*this.addEventListener(Event.ENTER_FRAME, moveY)
			this.addEventListener(Event.ENTER_FRAME, moveX)
			this.addEventListener(Event.ENTER_FRAME, moveZ)*/
			  
		 	//addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
		  	addEventListener(MouseEvent.MOUSE_UP, mouseReleasedHandler);			
		}
		
		public function updateSphere(roomArray:Array):void{
			
			var newDataArray:Array = new Array();
			var room:Room;
			for each (room in roomArray){
				newDataArray.push(new Broadcast(room));	
			}				
			sphere.update(newDataArray);
		}
		 
		// rotation functions
		/*private function moveY(e:Event):void {this.sphere.rotationY += 0.1;}
		private function moveX(e:Event):void {this.sphere.rotationX += 0.5;}
		private function moveZ(e:Event):void {this.sphere.rotationZ += 0.3;}*/
		
		private function mouseReleasedHandler(e:MouseEvent):void {
			
			if(sphere.activeElement != null) {
				if(activePanel.hitTestObject(sphere.activeElement)) {
					sphere.activeElement.isDragged = false;
					addElementToActive(new ActiveTopic(activePanel,sphere.activeElement.broadcast));
				} else {
					sphere.activeElement.moveBack();
				}
			}
			sphere.setActiveElement(null);
		}
		
		private function addElementToActive(element:ActiveTopic):void {
			element.x = mouseX;
			element.y = mouseY;
			element.addEventListener(MouseEvent.MOUSE_UP, mouseReleasedHandler);
			activePanel.addTopic(element);
		}
		
		public function speachSelected(speachId:int):void{
			dispatchEvent(new SelectedSpeachChanged('speachChanged', speachId));
		}
	}
}
